using System;
using UnityEngine;
using UnityEngine.Networking;
using Cysharp.Threading.Tasks;
using Net.Helper;
using Net.Unity;

namespace GameCore
{
    public class DownloadManager
    {
        public static async UniTask<bool> DownloadRequestTips(string title, string info)
        {
            return await Global.UI.Message.ShowUIAsync(title, info);
        }

        public static async UniTask<bool> DownloadFile(string url, string filePath, string name, Action<string, float> downloadUpdate = null)
        {
            var totalLength = await GetFileLength(url);
            return totalLength != 0L && await DownloadFile(url, filePath, name, 0L, totalLength, downloadUpdate);
        }

        public static async UniTask<bool> DownloadFile(string url, string filePath, string name, long currByteSize, long totalLength, Action<string, float> downloadUpdate = null)
        {
            return await UnityWebRequestEx.GetAsync(url, new FileDHParameter(filePath), oper =>
            {
                UpdateDownloadProgress(oper.webRequest, name, currByteSize, totalLength, downloadUpdate);
            },
            request =>
            {
                UpdateDownloadProgress(request, name, currByteSize, totalLength, downloadUpdate);
                return true;
            },
            async error =>
            {
                return (await Global.UI.Message.ShowUIAsync("下载资源", "下载资源失败,是否重试?"), false);
            },
            Global.Config.Timeout);
        }

        public static void UpdateDownloadProgress(UnityWebRequest request, string name, long currByteSize, long totalLength, Action<string, float> downloadCompleted)
        {
            var downloadedBytes = (long)request.downloadedBytes + currByteSize;
            var progressText = $"{name}下载进度:{downloadedBytes.ToByteString()}/{totalLength.ToByteString()}";
            if (downloadCompleted == null)
                Global.UI.Loading.ShowUI(progressText, downloadedBytes / (float)totalLength);
            else
                downloadCompleted(progressText, downloadedBytes / (float)totalLength);
        }

        public static async UniTask<long> GetFileLength(string url) //返回0肯定就是获取失败了
        {
            return await UnityWebRequestEx.GetAsync(url, "HEAD", new DHParameter(), null, requer =>
            {
                var totalLength = long.Parse(requer.GetResponseHeader("Content-Length"));
                return totalLength;
            },
            async error =>
            {
                Debug.LogError($"{url} 获取资源失败:" + error);
                return (await UniTask.FromResult(false), 0L);
            },
            Global.Config.Timeout);
        }
    }
}